package com.movie.controller;

import com.movie.model.User;
import com.movie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @ResponseBody
    public String login(@RequestBody User user, HttpSession session) {
        User loginUser = userService.login(user.getUsername(), user.getPassword());
        if (loginUser != null) {
            session.setAttribute("user", loginUser);
            return loginUser.getRole();
        }
        return "error";
    }

    @PostMapping("/register")
    @ResponseBody
    public String register(@RequestBody User user) {
        try {
            user.setRole("USER");
            userService.register(user);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }

    @GetMapping("/logout")
    @ResponseBody
    public String logout(HttpSession session) {
        session.invalidate();
        return "success";
    }
}